package com.xiuxia.usercenterbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiuxia.usercenterbackend.common.ResponseCode;
import com.xiuxia.usercenterbackend.common.exception.BusinessException;
import com.xiuxia.usercenterbackend.domain.User;
import com.xiuxia.usercenterbackend.mapper.UserMapper;
import com.xiuxia.usercenterbackend.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.xiuxia.usercenterbackend.constants.UserConstant.ADMIN_ROLE;
import static com.xiuxia.usercenterbackend.constants.UserConstant.USER_LOGIN_STATE;

/**
 * @author 17732
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2024-11-27 10:16:48
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "xiuxia";


    @Override
    public Long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 非空校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        // 2. 账户长度校验
        if (userAccount.length() < 6) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        // 3. 账户不能包含特殊字符
        String regex = "[^a-zA-Z0-9]";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        // 4. 密码长度校验
        if (userPassword.length() < 8) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        // 5. 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        // 6. 账户不能重复
        int count = this.count(new LambdaQueryWrapper<User>().eq(User::getUserAccount, userAccount));
        if (count > 0) {
            throw new BusinessException("账户已存在",ResponseCode.INTERNAL_ERROR);
        }
        //7.密码加密
        String encryptUserPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        User user = new User();
        user.setUserAccount(userAccount);
        user.setPassword(encryptUserPassword);
        boolean result = this.save(user);
        if (!result) {
            throw new BusinessException("添加用户失败",ResponseCode.INTERNAL_ERROR);
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 非空校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        // 2. 账户长度校验
        if (userAccount.length() < 6) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        // 3. 账户不能包含特殊字符
        String regex = "[^a-zA-Z0-9]";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        // 4. 密码长度校验
        if (userPassword.length() < 8) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        String encryptUserPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        User user = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserAccount, userAccount)
                .eq(User::getPassword, encryptUserPassword)
                .eq(User::getUserStatus, 0));
        if (user == null) {
            throw new BusinessException("用户不存在",ResponseCode.INTERNAL_ERROR);
        }
        //5. 用户脱敏
        User safeUser = getSafeUser(user);
        //6.生成登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safeUser);
        return safeUser;
    }

    /**
     * 搜索用户
     *
     * @param nickName 用户昵称
     * @param request  请求
     * @return List<User>
     */
    @Override
    public List<User> searchUsers(String nickName, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ResponseCode.NO_PERMISSION);
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNoneBlank(nickName)) {
            queryWrapper.like(User::getNickName, nickName);
        }
        List<User> userList = this.list(queryWrapper);
        return userList.stream().map(UserServiceImpl::getSafeUser).collect(Collectors.toList());

    }

    /**
     * 判断是否是管理员
     *
     * @param request 请求
     * @return boolean
     */
    private boolean isAdmin(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null || user.getUserRole() != ADMIN_ROLE) {
            return false;
        }
        return true;
    }

    /**
     * 删除用户
     *
     * @param id      用户id
     * @param request 请求
     * @return Boolean
     */
    @Override
    public Boolean deletedUser(Long id, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ResponseCode.NO_PERMISSION);
        }
        if (id == null || id < 1) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        return this.removeById(id);
    }

    @Override
    public User getUserCurrent(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user != null) {
            User userById = this.getById(user.getId());
            return getSafeUser(userById);
        }
        return null;
    }

    /**
     * 退出登录i
     *
     * @param request
     * @return
     */
    @Override
    public Integer userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 获取脱敏用户
     *
     * @param user 原用户信息
     * @return
     */
    public static User getSafeUser(User user) {
        if (user == null) {
            throw new BusinessException(ResponseCode.PARAM_ERROR);
        }
        User safeUser = new User();
        safeUser.setId(user.getId());
        safeUser.setUserAccount(user.getUserAccount());
        safeUser.setNickName(user.getNickName());
        safeUser.setAvatarUrl(user.getAvatarUrl());
        safeUser.setEmail(user.getEmail());
        safeUser.setPhoneNumber(user.getPhoneNumber());
        safeUser.setUserStatus(user.getUserStatus());
        safeUser.setGender(user.getGender());
        safeUser.setCreateTime(user.getCreateTime());
        safeUser.setUserRole(user.getUserRole());
        return safeUser;
    }
}




